package com.fw.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @ClassName AuthUtils
 * @Description TODO
 * @Authoe weiyan
 * @Date 2019/10/23 13:41
 * @Version 1.0
 **/
public class AuthUtils {

    //秘钥
    private String key;

    private long time;//过期时间 

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTime() {
        return time;
    }

    public void setTtl(long time) {
        this.time = time;
    }

    public AuthUtils() {
    }

    public AuthUtils(String key, long time) {
        this.key = key;
        this.time = time;
    }

    /**
     * 生成秘钥
     */
    public String createJWT(String id, String subject, String roles) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key).claim("roles", roles);//这是签名秘钥
        if (time == 0) {//默认为一小时
            builder.setExpiration(new Date(nowMillis + 3600000));
        } else {
            builder.setExpiration(new Date(nowMillis + time));
        }
        return builder.compact();
    }

    /**
     * 解析秘钥
     */
    public Claims parseJWT(String jwtStr) {
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }

   /* public static void main(String[] args) {
        AuthUtils authUtils = new AuthUtils("jinxin",0);
        String jwt = authUtils.createJWT("1", null, "null");
        Claims claims = authUtils.parseJWT(jwt);
        System.out.println(claims.getId());
    }*/

}